package com.xebest.web.controller.aftersales;

import com.github.pagehelper.PageHelper;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundSourceEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundStatusEnum;
import com.xebest.common.enums.erp.aftersales.VenOrderRefundTypeEnum;
import com.xebest.common.enums.erp.order.VenOrderPayChannelEnum;
import com.xebest.common.enums.erp.order.VenOrderPayStatusEnum;
import com.xebest.common.enums.erp.order.VenOrderPayTypeEnum;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.RequestUtil;
import com.xebest.config.ParamConfig;
import com.xebest.constant.XeConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenAfterSaleMsg;
import com.xebest.web.form.XeVenAfterSaleCheckForm;
import com.xebest.web.form.XeVenAfterSaleDelForm;
import com.xebest.web.form.XeVenAfterSaleDetailForm;
import com.xebest.web.form.XeVenOrderRefundQueryForm;
import com.xebest.web.model.XeVenOrderInfoEntity;
import com.xebest.web.model.XeVenOrderRefundEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenAfterSaleService;
import com.xebest.web.service.XeVenOrderReFundService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenAfterSaleDetailView;
import com.xebest.web.view.XeVenOrderRefundView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退款单相关Controller
 *
 * @author chenjing
 */
@RestController
@RequestMapping("orderRefund")
@Scope("prototype")
public class XeVenOrderRefundController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(XeVenOrderRefundController.class);//日志记录类
    @Autowired
    XeVenOrderReFundService reFundService;
    @Autowired
    private XeVenAfterSaleService xeVenAfterSaleService;
    @Autowired
    private ParamConfig paramConfig;

    @RequestMapping(value = "batchOrderRefund", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse batchOrderRefund(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                  BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("退款单审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String operatorContent = "";               //记录日志信息
        String refundCode = form.getFormCode();
        int checkStatus = form.getCheckStatus();
        String refusReason = form.getRefusReason();
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(refundCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //实发差异退款和取消订单退款 不允许被拒绝
        if (VenOrderRefundStatusEnum.BACKED.getValue().equals(checkStatus)
                && (VenOrderRefundTypeEnum.CANCLE.getValue().equals(entity.getRefundType())
                || VenOrderRefundTypeEnum.DIFFERENCE.getValue().equals(entity.getRefundType()))) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_SUPPORT_BACKTYPE);
        }
        if (!VenOrderRefundStatusEnum.PENDING.getValue().equals(entity.getRefundStatus())
                && !VenOrderRefundStatusEnum.CHECKED.getValue().equals(entity.getRefundStatus())
                && !VenOrderRefundStatusEnum.FAILED.getValue().equals(entity.getRefundStatus())
                && checkStatus == VenOrderRefundStatusEnum.BACKED.getValue()) {
            log.error("状态异常！退款单号{}，当前退款单状态{}，预更新状态{}", entity.getRefundCode(), entity.getRefundStatus(), checkStatus);
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        if (!VenOrderRefundStatusEnum.PENDING.getValue().equals(entity.getRefundStatus())
                && checkStatus == VenOrderRefundStatusEnum.CHECKED.getValue()) {
            log.error("状态异常！退款单号{}，当前退款单状态{}，预更新状态{}", entity.getRefundCode(), entity.getRefundStatus(), checkStatus);
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        if (VenOrderRefundStatusEnum.BACKED.getValue().equals(checkStatus)) {
            operatorContent = "拒绝退款单:" + refundCode + "的退款申请，拒绝原因：" + refusReason;
        } else if (VenOrderRefundStatusEnum.CHECKED.getValue().equals(checkStatus)) {
            operatorContent = "接受（确认）退款单:" + refundCode + "的退款请求，退款金额为" + entity.getRealRefundedAmount();
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setRefundStatus(checkStatus);
        entity.setRefusReason(refusReason);
        try {
            int flag = reFundService.updateOrderRefund(entity);
            if (flag > 0) {
                //插入日志信息
                insertMqLog("", refundCode, operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================审核退款单 异常================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 查看退款单列表
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryOrderRefundList", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse queryOrderRefundList(@RequestBody XeVenOrderRefundQueryForm form) {
        if (null == form) form = new XeVenOrderRefundQueryForm();
        if (StringUtils.isNotBlank(form.getFormIdType())) {
            //1=退款单号  2=售后单号 3=订单编号  4=商品名称 5=商品货号  6=客户账号 7=退货单号
            int formIdType = Integer.parseInt(form.getFormIdType());
            switch (formIdType) {
                case 1:   //退款单号
                    form.setRefundCode(form.getFormIdValue());
                    break;
                case 2:   //售后单号
                    form.setAfterSalesCode(form.getFormIdValue());
                    break;
                case 3:   //订单信息
                    form.setOrderId(form.getFormIdValue());
                    break;
                case 4:   //商品名称
                    form.setProName(form.getFormIdValue());
                    break;
                case 5:   //商品货号
                    form.setProNum(form.getFormIdValue());
                    break;
                case 6:   //客户账号
                    form.setLoginAccount(form.getFormIdValue());
                    break;
                case 7:   //退货单号
                    form.setRejectCode(form.getFormIdValue());
                    break;
                default:
                    break;
            }
        }


        String startTime = form.getFormStartTime();
        String endTime = form.getFormEndTime();
        //设定查询中日期为3个月以内
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            Boolean dateCm = DateUtil.comparableTime(startTime, endTime);
            if (!dateCm) {
                return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_DATE_COMPARABLE);
            }
        }
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)) {
            endTime = DateUtil.getDate(new Date());
            ;
            startTime = DateUtil.strToNMonth(endTime, -3);
        }
        if (StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = DateUtil.strToNMonth(endTime, -3);
        }
        if (StringUtils.isBlank(endTime) && StringUtils.isNotBlank(startTime)) {
            endTime = DateUtil.strToNMonth(startTime, 3);
        }
        int formTimeType = form.getFormTimeType();
        //1=创建时间 2=退款时间
        switch (formTimeType) {
            case 1:
                form.setCreateStartTime(startTime);
                form.setCreateEndTime(endTime);
                break;
            case 2:
                form.setRefundStartTime(startTime);
                form.setRefundEndTime(endTime);
            default:
                break;
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XePageInfo<XeVenOrderRefundView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        try {
            List<XeVenOrderRefundView> orderRefundViewList = reFundService.getOrderRefundList(form);
            xePageInfo = new XePageInfo<>(orderRefundViewList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderRefundViewList", orderRefundViewList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询退款单列表异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 删除退款单 (已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "delOrderRefund", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse delOrderRefund(@RequestBody XeVenAfterSaleDetailForm form) {
        String orderRefundCode = form.getRefundCode();
        if (StringUtils.isBlank(orderRefundCode)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(orderRefundCode, userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        entity.setModifyUser(userInfo.getUserName());
        entity.setDelFlag(VenDelEnum.YES.getValue());
        try {
            int flag = reFundService.updateOrderRefund(entity);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================删除退款单异常======================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 批量审核退款单
     *
     * @author chenjing
     */
    @RequestMapping(value = "batchOrderRefundList", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse batchOrderRefundList(@RequestBody @Validated XeVenAfterSaleCheckForm form,
                                      BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("退款单批量审核缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String operatorContent = "";               //记录日志信息
        String[] formCodes = form.getFormCodes();
        if (formCodes.length == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setFormCodes(formCodes);
        int checkStatus = form.getCheckStatus();
        String refusReason = form.getRefusReason();
        if (VenOrderRefundStatusEnum.BACKED.getValue().equals(checkStatus) && StringUtils.isBlank(refusReason)) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setModifyUser(userInfo.getUserName());
        form.setUserCode(userCode);
        if (VenOrderRefundStatusEnum.BACKED.getValue().equals(checkStatus)) {
            operatorContent = "批量拒绝退款单:" + formCodes + "的退款申请，拒绝原因：" + refusReason;
        } else if (VenOrderRefundStatusEnum.CHECKED.getValue().equals(checkStatus)) {
            operatorContent = "批量确认(接受)退款单:" + formCodes + "的退款请求";
        }
        try {
            int flag = reFundService.batchOrderRefundList(form);
            if (flag > 0) {
                //插入日志信息
                insertMqLog("", formCodes.toString(), operatorContent);
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================批量审核退款单 异常================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 查询退款单明细信息
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryRefundDetail", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse queryRefundDetail(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                   BindingResult result) {
        if (null == form) return sendAjaxError(BASEMessage.PARAM_ERROR);
        if (StringUtils.isBlank(form.getRefundCode())) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        if (null == entity) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //如果售后单为自动创建，则直接查询订单明细
        if (VenOrderRefundSourceEnum.AFTER_SALE.getValue().equals(entity.getRefundSource())) {
            form.setAfterSalesCode(entity.getAfterSalesCode());
        }
        form.setOrderId(entity.getOrderId());
        try {
            List<XeVenAfterSaleDetailView> refundDetailList = reFundService.queryRefundDetail(form);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("refundDetailList", refundDetailList);
            map.put("picServer", paramConfig.getImgUrl());
            map.put("picDir", XeConstans.ERP_PRO_PIC_DIR);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================查询退货单详细信息异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 批量删除退款单(已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "delRefundList", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse delRefundList(@RequestBody @Validated XeVenAfterSaleDelForm form,
                               BindingResult result) {

        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            log.info("退款单删除退货缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        String[] formCodes = form.getRefundFormCodes();
        if (formCodes.length == 0) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        form.setRefundFormCodes(formCodes);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setModifyUser(userInfo.getUserName());
        form.setUserCode(userCode);
        try {
            int flag = reFundService.delRefundList(form);
            if (flag > 0) return sendAjaxOK();
            else return sendAjaxError();
        } catch (Exception e) {
            log.error("================批量删除退款单异常 ================,{}", e);
            return sendAjaxError();
        }
    }


    /**
     * 批量同意退款（非微信支付渠道） (已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "refundAllByOnlinePay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse refundAllByOnlinePay(@RequestBody @Validated XeVenAfterSaleDelForm form,
                                      BindingResult result) {
        if (null == form || null == form.getRefundFormCodes()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        String operatorContent = "";               //记录日志信息
        String[] refundCodes = form.getRefundFormCodes();
        if (refundCodes.length > 10) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_LIST_NUM);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        try {
            Map map = reFundService.refundAllByOnlinePay(form);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================非微信支付退款（批量）异常 ================,{}", e);
            return sendAjaxError();
        }

    }


    /**
     * 批量同意退款（微信支付渠道）(已不用)
     *
     * @author chenjing
     */
    @RequestMapping(value = "refundAllByWxPay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse refundAllByWxPay(@RequestBody @Validated XeVenAfterSaleDelForm form,
                                  BindingResult result) {
        if (null == form || null == form.getRefundFormCodes()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        String[] refundCodes = form.getRefundFormCodes();
        if (refundCodes.length > 10) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_LIST_NUM);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        try {
            Map map = reFundService.refundAllByWxPay(form);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("================微信支付退款（批量）异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 同意退款（微信支付渠道）=单条
     *
     * @author chenjing
     */
    @RequestMapping(value = "refundByWxPay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse refundByWxPay(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                               BindingResult result) {
        if (null == form || null == form.getRefundCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        //验证退款单状态是否为已确认退款
        if (!VenOrderRefundStatusEnum.CHECKED.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证该退款单对应的订单是否是微信支付
        XeVenOrderInfoEntity orderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(entity.getOrderId(), userCode);
        if (!VenOrderPayChannelEnum.WECHAT.getValue().equals(orderInfoEntity.getPayChannel())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_SUPPORT_WXPAY);
        }
        //同意退款时如果订单为在线支付验证该退款单对应的订单状态是否为已发货
        if (VenOrderPayTypeEnum.ONLINE_PAY.getValue().equals(orderInfoEntity.getPayType()) &&
                (VenOrderStatusEnum.WAIT_SEND.getValue().equals(orderInfoEntity.getOrderStatus())
                        || VenOrderStatusEnum.WAIT_DIS.getValue().equals(orderInfoEntity.getOrderStatus())
                        || VenOrderStatusEnum.WAIT_CHECK.getValue().equals(orderInfoEntity.getOrderStatus()))) {
            return sendAjaxError(XeVenAfterSaleMsg.ORDER_STATUS_SEND_ERR);
        }
        try {
            boolean okFlag = reFundService.refundByWxPay(entity);
            if (okFlag) {
                //插入日志信息
                insertMqLog("", form.getRefundCode(), "微信支付同意退款,退款单号：" + form.getRefundCode());
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================微信支付同意退款异常 ================,{}", e);
            return sendAjaxError();
        }
    }


    /**
     * 同意退款（非微信支付渠道）=单条
     *
     * @author chenjing
     */
    @RequestMapping(value = "refundByOnlinePay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse refundByOnlinePay(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                   BindingResult result) {
        if (null == form || null == form.getRefundCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        //验证退款单状态是否为已确认退款
        if (!VenOrderRefundStatusEnum.CHECKED.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证该退款单对应的订单是否是微信支付
        XeVenOrderInfoEntity orderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(entity.getOrderId(), userCode);
        if (VenOrderPayChannelEnum.WECHAT.getValue().equals(orderInfoEntity.getPayChannel())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_NOSUPPORT_WXPAY);
        }
        //同意退款时如果订单为在线支付验证该退款单对应的订单状态是否为已发货
        if (VenOrderPayTypeEnum.ONLINE_PAY.getValue().equals(orderInfoEntity.getPayType()) &&
                (VenOrderStatusEnum.WAIT_SEND.getValue().equals(orderInfoEntity.getOrderStatus())
                        || VenOrderStatusEnum.WAIT_DIS.getValue().equals(orderInfoEntity.getOrderStatus())
                        || VenOrderStatusEnum.WAIT_CHECK.getValue().equals(orderInfoEntity.getOrderStatus()))) {
            return sendAjaxError(XeVenAfterSaleMsg.ORDER_STATUS_SEND_ERR);
        }
        try {
            boolean okFlag = reFundService.refundByOnlinePay(entity);
            if (okFlag) {
                insertMqLog("", form.getRefundCode(), "非微信支付同意退款,退款单号：" + form.getRefundCode());
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================非微信支付同意退款异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 同意退款（售后创建类型）=单条
     *
     * @author chenjing
     */
    @RequestMapping(value = "refundByAfterSale", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse refundByAfterSale(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                   BindingResult result) {
        if (null == form || null == form.getRefundCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        //验证退款单状态是否为已确认退款
        if (!VenOrderRefundStatusEnum.CHECKED.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证该退款单对应的订单是否是已支付
        XeVenOrderInfoEntity orderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(entity.getOrderId(), userCode);
        if (VenOrderPayStatusEnum.UNPAID.getValue().equals(orderInfoEntity.getPayStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_UNPAY_ORDER);
        }
        //验证该退款单对应的订单是否是售后类型创建
        if (!VenOrderRefundTypeEnum.AFTERSALERFUND.getValue().equals(entity.getRefundType())
                && !VenOrderRefundTypeEnum.AFTERSALEREJECT.getValue().equals(entity.getRefundType())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_SUPPORT_AFTERSALE);
        }
        // entity.setRefundStatus(VenOrderRefundStatusEnum.DONE.getValue());
        entity.setModifyUser(userInfo.getUserName());
        try {
            // int okFlag = reFundService.refundByAfterSale(entity);
            boolean okFlag = reFundService.refundByOnlinePay(entity);
            if (okFlag) {
                insertMqLog("", form.getRefundCode(), "售后类型创建退款单同意退款,退款单号：" + form.getRefundCode());
                return sendAjaxOK();
            } else return sendAjaxError();
        } catch (Exception e) {
            log.error("================售后创建类型退款单同意退款异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 微信支付手动同步状态
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryRefundMoneyDetailByWxPay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse queryRefundMoneyDetailByWxPay(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                               BindingResult result) {
        if (null == form || null == form.getRefundCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        //验证该退款单类型是否为售后类型
        if (VenOrderRefundTypeEnum.AFTERSALERFUND.getValue().equals(entity.getRefundType())
                || VenOrderRefundTypeEnum.AFTERSALEREJECT.getValue().equals(entity.getRefundType())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_NOSUPPORT_AFTERSALE);
        }
        if (VenOrderRefundStatusEnum.DONE.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证退款单状态是否为正在处理中
        if (!VenOrderRefundStatusEnum.DOING.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证该退款单对应的订单是否是微信支付
        XeVenOrderInfoEntity orderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(entity.getOrderId(), userCode);
        if (!VenOrderPayChannelEnum.WECHAT.getValue().equals(orderInfoEntity.getPayChannel())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_SUPPORT_WXPAY);
        }
        try {
            Map map = reFundService.queryRefundMoneyDetailByWxPay(entity);
            if ("2".equals(map.get("okSum"))) {
                insertMqLog("", form.getRefundCode(), "微信支付手动同步状态,退款单号：" + form.getRefundCode());
                return sendAjaxOK();
            } else {
                return sendAjaxError(map.get("msg").toString());
            }
        } catch (Exception e) {
            log.error("================微信支付手动同步状态异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 在线支付手动同步状态
     *
     * @author chenjing
     */
    @RequestMapping(value = "queryRefundMoneyDetailByOnlinePay", method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse queryRefundMoneyDetailByOnlinePay(@RequestBody @Validated XeVenAfterSaleDetailForm form,
                                                   BindingResult result) {
        if (null == form || null == form.getRefundCode()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        String userCode = userInfo.getUserCode();
        form.setUserCode(userCode);
        XeVenOrderRefundEntity entity = reFundService.getOrderRefundByRefundCode(form.getRefundCode(), userCode);
        //验证该退款单类型是否为售后类型
        if (VenOrderRefundTypeEnum.AFTERSALERFUND.getValue().equals(entity.getRefundType())
                || VenOrderRefundTypeEnum.AFTERSALEREJECT.getValue().equals(entity.getRefundType())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_NOSUPPORT_AFTERSALE);
        }
        if (VenOrderRefundStatusEnum.DONE.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证退款单状态是否为正在处理中
        if (!VenOrderRefundStatusEnum.DOING.getValue().equals(entity.getRefundStatus())) {
            return sendAjaxError(XeVenAfterSaleMsg.REFUND_STATUS_ERR);
        }
        //验证该退款单对应的订单是否是微信支付
        XeVenOrderInfoEntity orderInfoEntity = xeVenAfterSaleService.queryOrderInfoByOrderId(entity.getOrderId(), userCode);
        if (VenOrderPayChannelEnum.WECHAT.getValue().equals(orderInfoEntity.getPayChannel())) {
            return sendAjaxError(XeVenAfterSaleMsg.AFTER_SALE_REFUND_SUPPORT_WXPAY);
        }
        try {
            Map map = reFundService.queryRefundMoneyDetailByOnline(entity);
            if ("2".equals(map.get("okFlag"))) {
                insertMqLog("", form.getRefundCode(), "在线支付手动同步状态,退款单号：" + form.getRefundCode());
                return sendAjaxOK();
            } else {
                return sendAjaxError(map.get("msg").toString());
            }
        } catch (Exception e) {
            log.error("================在线支付手动同步状态异常 ================,{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 统一日志信息
     *
     * @author chenjing
     */
    private void insertMqLog(String logType, String key, String operatorContent) {
        try {
            String ipAddress = RequestUtil.getClientIpAddress(request);
            if (StringUtils.isBlank(logType)) {
                logType = ErpLogTypeEnum.erpAfterSaleRefund.getValue();
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            String userCode = userInfo.getUserCode();

            OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getUserName(), operatorContent, userCode);
        } catch (Exception e) {
            log.error("退款单相关MQ日志插入失败,logType={},operatorContent={}", logType, operatorContent);
        }
    }
}
